var EventEmitter = require("events").EventEmitter;
var event = new EventEmitter();

var mongoose = require("mongoose"),
    DB_URL = process.env["MONGODB_DB_URL"];

mongoose.connect(DB_URL);

mongoose.connection.on("connected", function () {
    console.log("Connected to MongoDB on " + DB_URL);
});

mongoose.connection.on("error", function (err) {
    console.log("MongoDB connection error: " + err);
});

mongoose.connection.on("disconnected", function () {
    console.log("MongoDB connection disconnected");
});

var Schema = mongoose.Schema;

var UserSchema = new Schema({
    username: {
        type: String
    },
    password: {
        type: String
    },
    salt: {
        type: String
    }
});

var User = mongoose.model("User", UserSchema);

function dbInsert(user) {
    user.save(function (err, res) {
        if (err) {
            console.log("MongoDB error happend:" + err);
        } else {
            console.log("New insert:" + res);
        };
    });
}

function dbQuery(wherestr, callback) {
    User.find(wherestr, function (err, res) {
        if (err) {
            console.log("MongoDB error happend:" + err);
        } else {
            console.log("New query:" + res);
            callback(res);
            event.emit("dbQueryOk");
        }
    });
}

module.exports = {
    dbInsert: dbInsert,
    dbQuery: dbQuery,
    dbState: event,
    dbUser: User
};